//
//  HOTProfileReviewViewController.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-9-12.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTProfileReviewViewController.h"
#import "HOTProfileModel.h"
#import "HOTEvaluationViewController.h"
#import "HOTSendMessageViewController.h"
#import "HOTMemoEditViewController.h"
#import "HOTFriendListViewController.h"
#import "HOTMessageChatViewController.h"
#import "HOTCostPopupHandler.h"
#import "HOTEvaluationListViewController.h"
#import <MessageUI/MessageUI.h>

@interface HOTProfileReviewViewController () <ZZZPopupViewDelegate, MFMailComposeViewControllerDelegate>{
    
    HOTUserInfo *_curUserinfo;
    NSString *_tUserId;
    HOTUserInfo *_updateUserInfo;
}

@end

@implementation HOTProfileReviewViewController

- (IBAction)rateViewClicked:(id)sender {
    
    NSString *targetUserId = @"";
    if (_tUserId) {
        
        targetUserId = _tUserId;
    } else {
        
        targetUserId = _curUserinfo.userId;
    }
    HOTEvaluationListViewController *elvc = [[HOTEvaluationListViewController alloc] initWithNibName:@"HOTEvaluationListViewController" bundle:nil userId:targetUserId];
    
    [self.navigationController pushViewController:elvc animated:YES];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil userInfo:(HOTUserInfo *)userInfo targetUserId:(NSString *)tUserId
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _curUserinfo = userInfo;
        _tUserId = tUserId;
    }
    return self;
}

-(void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    //_mainScrollView.contentSize = CGSizeMake(_mainScrollView.frame.size.width, ZZZ_calcY(_mainScrollView, 40));
    
    //contentScrollView.contentSize = CGSizeMake(contentScrollView.frame.size.width, ZZZ_calcY(_contentLabel, 20));
    
    
    //contentScrollView.layer.borderColor
    //CGSize size = [contentScrollView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNaviTitle:@"プロフィールレビュー"];
    
    [self addRightBtnTarget:self action:@selector(reportBtnClicked) image:[UIImage imageNamed:@"btn_report_off"] hImage:[UIImage imageNamed:@"btn_report_on"]];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_profile"]];
    
    _rateView.paddingW = 3;
    _rateView.userInteractionEnabled = YES;
    
    [_rateView setImagesDeselected:@"icon_star_off" partlySelected:@"icon_star2" fullSelected:@"icon_star_on" andDelegate:nil];
    [_rateView displayRating:0];
    
    [_showFollowerLab.layer setBorderWidth:2];
    [_showFollowerLab.layer setBorderColor:[[UIColor whiteColor] CGColor]];
    _showFollowerLab.userInteractionEnabled = YES;
    UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showFriendsBtnClicked)];
        
    [tgr setNumberOfTouchesRequired: 1];
    [tgr setNumberOfTapsRequired:1];
    
    [_showFollowerLab addGestureRecognizer:tgr];

    if (_tUserId) {
        
        [self requestDataFromNet];
    } else {
        
        _commentBtn.hidden = YES;
        _sendMessageBtn.hidden = YES;
        _followBtn.hidden = YES;
        _memoBtn.hidden = YES;
        [self updateView];
    }
}

- (void)reportBtnClicked {
    
    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *mailVc = [[MFMailComposeViewController alloc] init];
        mailVc.mailComposeDelegate = self;
        [mailVc setSubject:@"ユーザーに関する報告"];
        [mailVc setToRecipients:@[@"info@gen-para.com"]];
        [mailVc setMessageBody:[NSString stringWithFormat:@"報告するユーザー：%@\n報告されるユーザー：%@\n\nこのユーザーに関して報告したい内容を以下にご入力後送信ください。\n（例）投稿に不適切なコンテンツが多い\n",self.userInfo.userId,_tUserId] isHTML:NO];
        [self presentViewController:mailVc animated:YES completion:nil];
    }
}

-(void)showFriendsBtnClicked {
    
    NSLog(@"showFriendsBtnClicked");
    
    NSString *targetUserId = @"";
    if (_tUserId) {
        
        targetUserId = _tUserId;
    } else {
        
        targetUserId = _curUserinfo.userId;
    }
    HOTFriendListViewController *flvc = [[HOTFriendListViewController alloc] initWithNibName:@"HOTFriendListViewController" bundle:nil targetUid:targetUserId];
    [self.navigationController pushViewController:flvc animated:YES];
}

-(void)updateView {
    
    _nickNameLab.text = _curUserinfo.nick;
    
    _sexLabel.text = _curUserinfo.sexName;
    
    _birthdayLabel.text = _curUserinfo.birth;
    
    _bloodLabel.text = _curUserinfo.bloodName;
    
    healthLabel.text = _curUserinfo.healthName;
    
    _cityLabel.text = _curUserinfo.cityName;
    
    jobType.text = _curUserinfo.job_name;
    
    _capacityLabel.text = _curUserinfo.certificationName;
    
    _friendsLabel.text = [NSString stringWithFormat:@"%@人",_curUserinfo.follow_sum];
    
    [_rateView displayRating:_curUserinfo.rate.floatValue];
    
    _contentLabel.text = _curUserinfo.self_intro;
}

-(void)requestDataFromNet {
    
    [self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_TARGET_UID:_tUserId
                                 };
    
    __unsafe_unretained HOTProfileReviewViewController *tempObj = self;
    [self requestWithURL:HOT_URL_USER_GET_INFO Parameters:parameters success:^(NSInteger result, NSDictionary * userInfo) {
       
        if (userInfo) {
            //更新界面
            [tempObj updateView:userInfo];
        }
        [tempObj loadingSuccess];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(void)updateView:(NSDictionary *)userInfo_ {
    
    HOTUserInfo *userInfo = [[HOTUserInfo alloc] init];
    
    //update userInfo
    userInfo.nick = [HOTUtils getString:[userInfo_ objectForKey:@"user_nick"]];
    userInfo.email = [HOTUtils getString:[userInfo_ objectForKey:@"user_email"]];
    userInfo.pwd = [HOTUtils getString:[userInfo_ objectForKey:@"user_pwd"]];
    userInfo.sex = [HOTUtils getString:[userInfo_ objectForKey:@"user_sex"]];
    userInfo.birth = [HOTUtils getString:[userInfo_ objectForKey:@"user_birth"]];
    userInfo.city_id = [HOTUtils getString:[userInfo_ objectForKey:@"city_id"]];
    
    userInfo.blood = [HOTUtils getString:[userInfo_ objectForKey:@"blood"]];
    userInfo.health = [HOTUtils getString:[userInfo_ objectForKey:@"health"]];
    userInfo.district = [HOTUtils getString:[userInfo_ objectForKey:@"district"]];
    userInfo.self_intro = [HOTUtils getString:[userInfo_ objectForKey:@"self_intro"]];
    userInfo.job_id = [HOTUtils getString:[userInfo_ objectForKey:@"job_id"]];
    userInfo.job_name = [HOTUtils getString:[userInfo_ objectForKey:@"job_name"]];
    userInfo.certification = [HOTUtils getString:[userInfo_ objectForKey:@"certification_id"]];
    userInfo.rate = [HOTUtils getString:[userInfo_ objectForKey:@"rate"]];
    userInfo.follow_sum = [HOTUtils getString:[userInfo_ objectForKey:@"follow_sum"]];
    
    _nickNameLab.text = userInfo.nick;
    
    _birthdayLabel.text = userInfo.birth;

    _bloodLabel.text = [userInfo bloodName];
    
    jobType.text = [userInfo jobName];
    
    _capacityLabel.text = userInfo.certificationName;
    
    healthLabel.text = userInfo.healthName;

    _cityLabel.text = userInfo.cityName;
    
    _contentLabel.text = userInfo.self_intro;
    
    _friendsLabel.text = [NSString stringWithFormat:@"%@人",userInfo.follow_sum];
    
    _sexLabel.text = [userInfo sexName];
    
    NSString *isFollowed = [userInfo_ objectForKey:@"is_followed"];
    if ([isFollowed isEqualToString:@"1"]) {
        
        _followBtn.selected = YES;
    } else {
        _followBtn.selected = NO;
    }
    
    
    [_rateView displayRating:userInfo.rate.floatValue];
    
    _updateUserInfo = userInfo;
}

/**
 *  关注此人
 */
-(void)doFriendIn {
    
    [self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_TARGET_ID:_tUserId};
    
    __unsafe_unretained HOTProfileReviewViewController *tempObj = self;
    [self requestWithURL:HOT_URL_FRIEND_IN Parameters:parameters success:^(NSInteger result, NSDictionary * data) {
        
        [tempObj showSuccessWithMessage:MSG_SUCCESS complection:^{
            
            [self requestDataFromNet];
        }];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

/**
 *  取消关注此人
 */
-(void)doFriendOff {
    
    [self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_TARGET_ID:_tUserId};
    
    __unsafe_unretained HOTProfileReviewViewController *tempObj = self;
    [self requestWithURL:HOT_URL_FRIEND_DEL Parameters:parameters success:^(NSInteger result, NSDictionary * data) {
        
        [tempObj showSuccessWithMessage:MSG_SUCCESS complection:^{
            
            [self requestDataFromNet];
        }];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(void)popupView:(ZZZPopupView *)popupView buttonKind:(ZZZPopupViewBtnKind)btnKind {
    [super popupView:popupView buttonKind:btnKind];
    if (popupView.tag == 101 && btnKind == ZZZPopupViewConfirmBtnKind) {
        
        if (!_followBtn.isSelected) {
            
            [self doFriendIn];
        } else {
            [self doFriendOff];
        }
        
    }
}

//navc pop 后会执行此代码
-(void)afterPopWithViewController:(UIViewController *)vc {
    
    [self requestDataFromNet];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)sendMessageBtnClicked:(id)sender {
    
//    HOTSendMessageViewController *smvc = [[HOTSendMessageViewController alloc] initWithNibName:@"HOTSendMessageViewController" bundle:nil userId:_tUserId];
//    
//    [self.navigationController pushViewController:smvc animated:YES];
    
    __unsafe_unretained HOTProfileReviewViewController *tempObj = self;
    [[HOTCostPopupHandler costPopupHandler] showWithPopupStyle:HOTCostPopupStyle2
                                                      userInfo:nil
                                                        cancel:nil
                                                       confirm:^{
                                                           
                                                           HOTMessageChatViewController *mcvc = [[HOTMessageChatViewController alloc] initWithNibName:@"HOTMessageChatViewController" bundle:nil conv_type:CONV_TYPE_OTHER target_uid:_tUserId];
                                                           
                                                           
                                                           [tempObj.navigationController pushViewController:mcvc animated:YES];
                                                       }];
    
}

- (IBAction)commentBtnClicked:(id)sender {
    
    HOTEvaluationViewController *evc = [[HOTEvaluationViewController alloc] initWithNibName:@"HOTEvaluationViewController" bundle:nil uid:_tUserId];
    [self.navigationController pushViewController:evc animated:YES];
}


- (IBAction)friendInBtnClicked:(id)sender {
    
    ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                          message:MSG_IS_FLOWING
                                                         delegate:self
                                                cancelButtonTitle:ALERT_BTN_CANCEL
                                                 otherButtonTitle:ALERT_BTN_OK];
    popupView.tag = 101;
    [popupView showInWindow];
}

- (IBAction)memoBtnClicked:(id)sender {
    
    HOTMemoEditViewController *mivc = [[HOTMemoEditViewController alloc] initWithNibName:@"HOTMemoEditViewController" bundle:nil noteInfo:@{@"target_id":_tUserId, @"type":@"1", @"user_nick":_updateUserInfo.nick}];
    
    [self.navigationController pushViewController:mivc animated:YES];
}

#pragma mark - mailDelegate

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [self dismissViewControllerAnimated:YES completion:nil];
    if (result == MFMailComposeResultCancelled) {
        NSLog(@"Message cancelled");
    } else if (result == MFMailComposeResultSent) {
         NSLog(@"Message Sent");
    } else if (result == MFMailComposeResultFailed) {
        NSLog(@"Message failed");
    } else if (result == MFMailComposeResultSaved) {
        NSLog(@"Message saved");
    } else {
        NSLog(@"Unknown error");
    }
}


@end
